extends Control

#节点加载---start
@onready var mahjong_animated = $MahjongAnimated
@onready var mahjong_img = $MahjongImg
@onready var mahjong_btn = $MahjongTileBtn
@onready var mahjong_bg = $MahjongBg
@onready var audio_stream_player = $AudioStreamPlayer
#节点加载---end

@export var mahjong_id: String = ""

var parentGameProgress
var new_texture

func _ready() -> void:
	mahjong_img.mouse_filter = Control.MOUSE_FILTER_IGNORE
	var mahjongId = mahjong_id.split("_")[0] + "_" + mahjong_id.split("_")[1]
	var imgPathStr = "res://assets/image/mahjong/" + mahjongId +".png"
	new_texture = load(imgPathStr)
	var parent = get_parent()  # 获取父节点
	if parent:
		var grandParent = parent.get_parent()  # 获取父节点的父节点（即祖父节点）
		parentGameProgress = grandParent.gameProgress #获取游戏进程
		#回合开始时，播放翻牌动画
		if parentGameProgress == 1:
			mahjong_animated.play()
	
func _process(delta):
	if mahjong_animated.frame == 3:
		mahjong_animated.visible = false
		if new_texture:
			mahjong_bg.visible = true
			mahjong_img.texture = new_texture
			mahjong_img.visible = true
		else:
			pass

#麻将牌点击事件
func _on_mahjong_tile_btn_pressed() -> void:
	audio_stream_player.play(0.11) #播放点击麻将音效
	var root = get_tree().current_scene.play_scene
	# 最大选择牌数限制
	if root.selectedTileIdArr.size() >= PlayerDetail.maxSelected and not root.selectedTileIdArr.has(self.mahjong_id):
		return
	# 处理麻将牌的选中/取消选中
	if root:
		if root.selectedTileIdArr.has(self.mahjong_id):
			root.selectedTileIdArr.erase(self.mahjong_id)  # 如果已经选中了，再次点击会取消选择
			self.position.y += 20  # 将牌位置向上移动
		else:
			root.selectedTileIdArr.append(self.mahjong_id)  # 添加到选择列表
			self.position.y -= 20  # 将牌位置向下移动（恢复原位）
	if root.selectedTileIdArr.size() > 0:
		root.showButton()
	else:
		root.hideButton()
